package jlxy.ise.eroad.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cz.msebera.android.httpclient.Header;
import jlxy.ise.eroad.R;
import jlxy.ise.eroad.activity.LoginActivity;
import jlxy.ise.eroad.activity.TabMainActivity;
import jlxy.ise.eroad.base.BaseSwitchFragment;
import jlxy.ise.eroad.bean.DriverInfo;
import jlxy.ise.eroad.bean.ServerRpsInfo;
import jlxy.ise.eroad.util.C;
import jlxy.ise.eroad.util.SPUtils;
import jlxy.ise.eroad.util.SingleToast;
import jlxy.ise.eroad.util.WebUtil;


/**
 * 登录界面
 *
 * @author chen
 */
public class LoginFragment extends BaseSwitchFragment implements OnClickListener {

    private TextView mBtnLogin;
    private TextView mBtnReg;
    private TextView mBtnFrgpwd;
    private EditText mEtPhone;
    private EditText mEtPwd;

    private CheckBox mCkRemberPwd;

    private View mPrgView;
    private View mInputLayout;

    private int back = 0;// 判断按几次back
    private float mWidth, mHeight;
    private LinearLayout mName, mPsw;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_login, container,
                false);

        mPrgView = rootView.findViewById(R.id.layout_progress);
        mInputLayout = rootView.findViewById(R.id.input_layout);

        mName = (LinearLayout) rootView.findViewById(R.id.input_layout_name);
        mPsw = (LinearLayout) rootView.findViewById(R.id.input_layout_psw);

        mBtnLogin = (TextView) rootView.findViewById(R.id.button_login);
        mBtnReg = (TextView) rootView.findViewById(R.id.button_register);
        mBtnFrgpwd = (TextView) rootView
                .findViewById(R.id.button_forget_password);
        mEtPhone = (EditText) rootView
                .findViewById(R.id.editText_userName);
        mEtPwd = (EditText) rootView
                .findViewById(R.id.editText_userPassword);
        mCkRemberPwd = (CheckBox) rootView.findViewById(R.id.cb_rememberpwd);

        mCkRemberPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                SPUtils.setParam(mAct, C.SP.REMEMBER_LOGIN, arg1);
            }
        });

        Boolean isRemember = (Boolean) SPUtils.getParam(mAct,
                C.SP.REMEMBER_LOGIN, true);
        mCkRemberPwd.setChecked(isRemember);
        if (isRemember) {
            String userAccount = (String) SPUtils.getParam(mAct, C.SP.ACCOUNT, "");
            String userPassword = (String) SPUtils.getParam(mAct, C.SP.PWD, "");

            if (!TextUtils.isEmpty(userAccount)
                    && !TextUtils.isEmpty(userPassword)) {
                mEtPhone.setText(userAccount);
                mEtPwd.setText(userPassword);
            }
        }
        mBtnLogin.setOnClickListener(this);
        mBtnReg.setOnClickListener(this);
        mBtnFrgpwd.setOnClickListener(this);
        mAct.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        return rootView;

    }


    // 显示登陆错误对话框
    private void showLoginError() {
        new AlertDialog.Builder(mAct)
                .setTitle(
                        mAct.getResources().getString(
                                R.string.dialog_error_title))
                .setMessage(
                        mAct.getResources().getString(
                                R.string.error_login_error))
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                mInputLayout.setVisibility(View.VISIBLE);
                                mName.setVisibility(View.VISIBLE);
                                mPsw.setVisibility(View.VISIBLE);
                                mInputLayout.setScaleX(1.0f);
                                mPrgView.setVisibility(View.GONE);
                            }
                        }).show();
    }

    // 显示密码为空对话框
    private void showUserPasswordEmptyError() {
        new AlertDialog.Builder(mAct)
                .setTitle(
                        mAct.getResources().getString(
                                R.string.dialog_error_title))
                .setMessage(
                        mAct.getResources().getString(
                                R.string.error_register_password_null))
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }
                        }).show();
    }

    // 显示用户名为空对话框
    private void showUserNameEmptyError() {
        new AlertDialog.Builder(mAct)
                .setTitle(
                        mAct.getResources().getString(
                                R.string.dialog_error_title))
                .setMessage(
                        mAct.getResources().getString(
                                R.string.error_register_user_name_null))
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }
                        }).show();
    }

    public void doFragmentBackPressed() {
        back++;
        switch (back) {
            case 1:
                SingleToast.showToast(mAct, R.string.exit_again, 3000);
                // 3秒内都可以退出应用
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        back = 0;
                    }
                }, 3000);
                break;
            case 2:
                back = 0;
                if (TextUtils.isEmpty(mEtPhone.getText())
                        || TextUtils.isEmpty(mEtPwd.getText())) {
                    SPUtils.setParam(mApp, C.SP.REMEMBER_LOGIN, false);
                }
                mAct.finish();
                android.os.Process.killProcess(android.os.Process.myPid());// 关闭进程
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_login:
                String phoneStr = mEtPhone.getText().toString();
                if (phoneStr.isEmpty()) {
                    showUserNameEmptyError();
                    return;
                }
                String pwd = mEtPwd.getText().toString();
                if (pwd.isEmpty()) {
                    showUserPasswordEmptyError();
                    return;
                }

                // 进行登录验证
                WebUtil.postLoginVerify(WebUtil.getRpLoginVerify(phoneStr, pwd), new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        Gson gson = new Gson();
                        try {
                            ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                            if (serverRpsInfo.getStatus().equals("ok") && serverRpsInfo.getMessage().equals("ok")) {
                                DriverInfo driverInfo = gson.fromJson(response.toString(), DriverInfo.class);
                                if (!driverInfo.getData().isEmpty()) {
                                    //说明存在此司机数据
                                    mApp.setDriverInfo(driverInfo.getData().get(0));
                                    //进入主界面
                                    if (mCkRemberPwd.isChecked()) {
                                        SPUtils.setParam(mAct, C.SP.ACCOUNT,
                                                mEtPhone.getText().toString());
                                        SPUtils.setParam(mAct, C.SP.PWD,
                                                mEtPwd.getText().toString());
                                    } else {
                                        SPUtils.setParam(mAct, C.SP.ACCOUNT, "");
                                        SPUtils.setParam(mAct, C.SP.PWD, "");
                                    }

                                    //修改登录状态为上线
                                    Date date = new Date();
                                    SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                                    String currentTime = time.format(date);
                                    WebUtil.postLoginAlter(WebUtil.getRpLoginAlter(getDriverInfo().getId() + "", "1", currentTime), new JsonHttpResponseHandler() {

                                        @Override
                                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                            super.onSuccess(statusCode, headers, response);
                                            Gson gson = new Gson();
                                            try {
                                                ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                                                if (serverRpsInfo.getStatus().equals("ok") && serverRpsInfo.getMessage().equals("ok")) {
//						SingleToast.showToast(getApplicationContext(), "用户已上线", 2000);
                                                }
                                            } catch (Exception e) {
                                                //SingleToast.showToast(getApplicationContext(), "修改用户状态出错:" + e.getLocalizedMessage(), 2000);
                                            }
                                        }

                                        @Override
                                        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                            super.onFailure(statusCode, headers, throwable, errorResponse);
                                            //SingleToast.showToast(getApplicationContext(), "修改用户状态失败", 2000);
                                        }
                                    });

                                    Intent mainIntent = new Intent(mAct,
                                            TabMainActivity.class);
                                    startActivity(mainIntent);
                                    mAct.finish();
                                } else {
                                    SingleToast.showToast(mAct, "登录失败，没有找到对应信息", 2000);
                                }

                            }
                        } catch (Exception e) {
                            SingleToast.showToast(mAct, "登录出错:" + e.getLocalizedMessage(), 2000);
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        super.onFailure(statusCode, headers, throwable, errorResponse);
                        SingleToast.showToast(mAct, "登录失败", 2000);
                    }
                });
                break;
            case R.id.button_register:
                mFragmentCallBack.fragmentCallBack(LoginActivity.JUMP_2_REG, null);
                break;
            case R.id.button_forget_password:
                mFragmentCallBack.fragmentCallBack(LoginActivity.JUMP_2_FRG, null);
                break;
            default:
                break;
        }

    }


}
